<template>
  <div>
    <el-form :inline="true">
      <!--ystsn查询-->
      <el-form-item>
        <el-input v-model="badStockDto.queryYstsn" clearable placeholder="YSTSN">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-select style="width:180px;" v-model="badStockDto.faultAppearance" clearable placeholder="请选择硬件故障现象">
          <el-option
            v-for="item in hardwareFaultAppearance"
            :key="item.id"
            :label="item.appearance"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <v-distpicker only-province @selected="onSelected" v-if="badStockDto.roleType === 1">
        </v-distpicker>
        <el-select style="width:180px;" v-model="badStockDto.cityCode" placeholder="请选择地市"
                   v-if="(badStockDto.roleType === 2 && officeType === '0')
                           || (badStockDto.roleType === 3 && outsourceType === '1')">
          <el-option
            v-for="item in addressOption"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <!--网点类型查询-->
      <el-form-item v-if="badStockDto.roleType === 1">
        <el-select v-model="badStockDto.pointType" placeholder="请选择网点类型">
          <el-option
            v-for="item1 in pointTypeOptions"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select style="width:120px;" v-model="badStockDto.modelId" clearable placeholder="请选择型号">
          <el-option
            v-for="item in allModel"
            :key="item.id"
            :label="item.code"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select style="width:150px;" v-model="badStockDto.factoryId" placeholder="请选择返回工厂" clearable
                   @change="returnFactoryChange"
                   v-if="badStockDto.roleType === 2 || badStockDto.roleType === 3">
          <el-option
            v-for="item1 in returnFactoryOptions"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!--入库时间段查询-->
      <el-form-item>
        <el-date-picker
          v-model="badStockDto.inStockTime" clearable
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="入库时间段开始日期"
          end-placeholder="入库时间段结束日期">
        </el-date-picker>
      </el-form-item>
      <!--<el-form-item>-->
      <!--<el-button type="primary" @click="allReturn()" v-if="preOfficeType === '0' || preOfficeType === '1'">全部返还-->
      <!--</el-button>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="primary" @click="searchDate()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="returnDevice()"
                   v-if="badStockDto.roleType === 2 || badStockDto.roleType === 3">设备返还
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="specialReturnConfirm()"
                   v-if="badStockDto.roleType === 2 || badStockDto.roleType === 3">特殊返厂
        </el-button>
      </el-form-item>
    </el-form>
    <el-tabs type="border-card">
      <el-tab-pane label="待返厂">
        <custom-table
          :multipleSelection="true"
          :data="badStockList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :operationColumn="operationColumn"
          :pagination="pagination"
          @selection-change="selectionChange">
        </custom-table>
      </el-tab-pane>
      <el-tab-pane label="在途返厂维修">
        <custom-table
          :data="alreadyBackList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :pagination="pagination1"></custom-table>
      </el-tab-pane>
      <el-tab-pane label="工厂已收机">
        <custom-table
          :data="alreadyReceiveList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :pagination="pagination2"></custom-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="维修记录" :visible.sync="detailDialogVisible" :close-on-click-modal="false">
      <repair-list
        :ystsn="ystsn">
      </repair-list>
      <div slot="footer">
        <el-button type="primary" @click="onBtnCancel()">取消</el-button>
      </div>
    </el-dialog>
    <!--特殊返厂-->
    <el-dialog :title="'指定返还工厂'" center :visible.sync="specialReturnBoxVisible" wdith="100%"
               :close-on-click-modal="false">
      <el-form class="form-horizontal" style="text-align: left">
        <el-form-item label="返还工厂" prop="factoryId" label-width="150px">
          <el-select v-model="returnfactoryId" placeholder="请选择返还工厂"
                     v-if="badStockDto.roleType === 2 || badStockDto.roleType === 3">
            <el-option
              v-for="item1 in returnFactoryOptions"
              :key="item1.id"
              :label="item1.name"
              :value="item1.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="1" style="margin-left: 30%">
            <el-button @click="specialReturnBoxVisible = false">取消</el-button>
          </el-col>
          <el-col :span="5" style="margin-left: 10%">
            <el-button type="primary" @click="specialReturnReturn()">确定</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiGetBadStockList, apiGetReturnFactory} from '@/api/stock/index'
  import {parseTime} from '@/utils'
  import RepairList from '../../../components/table/RepairList.vue'
  import {
    getRoleType,
    getOfficeType,
    getOfficeProvinceCode,
    getCityCode,
    getProvinceCode,
    getOutsourceType,
    getOutsourceProvinceCode,
    getOutsourceCityCode
  } from '@/utils/token'
  import {apiGetCityListByProvinceCode, apiGetFaultAppearance, apiGetModelList} from '@/api/dictionary'

  export default {
    components: {
      RepairList,
      CustomTable
    },
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        status: 5,
        province: this.badStockDto.provinceCode,
        city: this.badStockDto.cityCode,
        pointType: this.badStockDto.pointType,
        factoryId: this.badStockDto.factoryId,
        ystsn: this.badStockDto.ystsn,
        faultAppearance: this.badStockDto.faultAppearance,
        modelId: this.badStockDto.modelId
      }
      let oper = {name: '返厂维修', callback: this.oneDeviceReturn, page: 'factoryRepair'}
      this.selectReturnFactoryInit()
      this.getAllModel()
      this.preRoleType = getRoleType()
      if (getRoleType() === '2') {
        this.operationColumn.operations.push(oper)
        this.badStockDto.roleType = 2
        this.badStockDto.pointType = 0
        listQuery.province = getProvinceCode()
        if (getOfficeType() === '1') {
          listQuery.city = getCityCode()
        }
        this.selectedAddressInit()
      } else if (getRoleType() === '3') {
        this.operationColumn.operations.push(oper)
        this.badStockDto.roleType = 3
        this.badStockDto.pointType = 1
        listQuery.province = getOutsourceProvinceCode()
        if (getOutsourceType() === '0') {
          listQuery.city = getOutsourceCityCode()
        }
        this.selectedAddressInit()
      }
      this.getBadStockList(listQuery)
      let alreadyBackDto = {
        pageNumber: this.pagination1.currentPage,
        pageSize: this.pagination1.pageSize,
        status: 2,
        province: this.badStockDto.provinceCode,
        city: this.badStockDto.cityCode,
        pointType: this.badStockDto.pointType,
        factoryId: this.badStockDto.factoryId,
        faultAppearance: this.badStockDto.faultAppearance,
        modelId: this.badStockDto.modelId
      }
      this.getAlreadyBackList(alreadyBackDto)
      let alreadyReceiveDto = {
        pageNumber: this.pagination2.currentPage,
        pageSize: this.pagination2.pageSize,
        status: 3,
        province: this.badStockDto.provinceCode,
        city: this.badStockDto.cityCode,
        pointType: this.badStockDto.pointType,
        factoryId: this.badStockDto.factoryId,
        faultAppearance: this.badStockDto.faultAppearance,
        modelId: this.badStockDto.modelId
      }
      this.getAlreadyReceiveList(alreadyReceiveDto)
      this.selectHardWareFaultAppearance()
    },
    data () {
      return {
        tableLoadingFlag: false,
        // 不良品库存一览表
        columns: [
          {label: '返还工厂', name: 'returnFactory', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', width: '100', align: 'center'},
          {label: '省份', name: 'provinceName', align: 'center'},
          {label: '城市', name: 'cityName', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: '210', align: 'center'},
          {label: '备机状态', name: 'isReturn', width: '100', align: 'center'},
          {label: '故障现象', name: 'appearance', width: '100', align: 'center'},
          {label: '入库时间', name: 'inStockTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '保修截止日期', name: 'deadLine', align: 'center', width: '160', formatter: this.formatTime},
          {label: '在库状态', name: 'statusStr', align: 'center'}
        ],
        pointTypeOptions: [
          {
            'id': 0,
            'name': '办事处'
          },
          {
            'id': 1,
            'name': '外包商'
          }
        ],
        badStockList: [],
        alreadyBackList: [],
        alreadyReceiveList: [],
        allModel: [],
        badStockDto: {
          provinceCode: '',
          cityCode: '',
          status: 5,
          pointType: 0,
          roleType: 1,
          factoryId: null,
          ystsn: '',
          queryYstsn: '',
          faultAppearance: '',
          modelId: '',
          inStockTime: []
        },
        operationColumn: {
          width: '150',
          operations: [
            {name: '维修病例', callback: this.onBtnRepairHistory}
          ]
        },
        detailTableLoadingFlag: false,
        detailDialogVisible: false,
        pagination: this.getData(this.getBadStockList),
        pagination1: this.getData(this.getAlreadyBackList),
        pagination2: this.getData(this.getAlreadyReceiveList),
        returnFactoryOptions: [],
        multipleSelectionList: [],
        hardwareFaultAppearance: [],
        idArrays: [],
        repairHistoryDto: {
          type: 0,
          ystsn: ''
        },
        ystsn: '',
        addressOption: [],
        // 特殊返厂弹出框显示
        specialReturnBoxVisible: false,
        returnfactoryId: '',
        outsourceType: getOutsourceType(),
        officeType: getOfficeType()
      }
    },
    methods: {
      // 获取设备型号一览
      getAllModel () {
        apiGetModelList().then(response => {
          this.allModel = response.data
        })
      },
      formatTime (row, column, cellValue) {
        if (column.property === 'deadLine') {
          return parseTime(cellValue, '{y}-{m}-{d}')
        } else {
          return parseTime(cellValue)
        }
      },
      // 全部返还
      allReturn () {
        if (this.badStockDto.factoryId === 0 || this.badStockDto.factoryId === null) {
          this.$alert('请选择返还工厂', '返还失败', {
            confirmButtonText: '确定'
          })
          return
        }
        if (this.badStockList.length === 0) {
          this.$alert('请选择需要返还的设备', '返还失败', {
            confirmButtonText: '确定'
          })
          return
        }
        this.$confirm('不良品全部返厂维修, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let factory = []
          let ystsn = []
          let deviceList = []
          let allBadDevice = this.badStockList
          for (let i in allBadDevice) {
            if (this.badStockDto.factoryId === allBadDevice[i].returnFactoryId) {
              deviceList.push(allBadDevice[i])
            }
          }
          for (let i in deviceList) {
            factory.push(deviceList[i].id)
            ystsn[i] = deviceList[i].ystsn
          }
          this.$router.push({
            path: '/stock/logistic',
            query: {
              type: 2,
              factoryId: this.badStockDto.factoryId,
              idArrays: factory,
              ystsn: ystsn
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消返厂'
          })
        })
      },
      selectHardWareFaultAppearance () {
        let listQuery = {
          faultType: 1
        }
        apiGetFaultAppearance(listQuery).then(response => {
          this.hardwareFaultAppearance = response.data
        })
      },
      // 地址初始化
      selectedAddressInit () {
        let listquery = {
          province: ''
        }
        if (this.preRoleType === '2' && this.officeType === '0') {
          listquery.province = getOfficeProvinceCode()
        } else if (this.preRoleType === '3' && this.outsourceType === '1') {
          listquery.province = getOutsourceProvinceCode()
        }
        apiGetCityListByProvinceCode(listquery).then(response => {
          let cityList = response.data
          let city = []
          let temp = {}
          for (let i in cityList) {
            if (!temp[cityList[i].name]) {
              temp[cityList[i].name] = cityList[i].code
            }
          }
          city.push({'name': '全部地市', 'code': ''})
          for (let k in temp) {
            city.push({'name': k, 'code': temp[k]})
          }
          this.addressOption = city
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 可返厂一览选择
      selectReturnFactoryInit () {
        apiGetReturnFactory().then(response => {
          let factoryList = response.data
          let factory = []
          let temp = {}
          for (let i in factoryList) {
            if (!temp[factoryList[i].name]) {
              temp[factoryList[i].name] = factoryList[i].id
            }
          }
          for (let k in temp) {
            factory.push({'name': k, 'id': temp[k]})
          }
          this.returnFactoryOptions = factory
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      getBadStockList (listQuery) {
        // TODO 获取库存一览表
        this.tableLoadingFlag = true
        listQuery.status = 5
        listQuery.province = this.badStockDto.provinceCode
        listQuery.city = this.badStockDto.cityCode
        listQuery.pointType = this.badStockDto.pointType
        listQuery.factoryId = this.badStockDto.factoryId
        listQuery.ystsn = this.badStockDto.ystsn
        listQuery.queryYstsn = this.badStockDto.queryYstsn
        listQuery.faultAppearance = this.badStockDto.faultAppearance
        listQuery.modelId = this.badStockDto.modelId
        if (this.badStockDto.inStockTime !== undefined && this.badStockDto.inStockTime !== null) {
          listQuery.inStockStartTime = this.badStockDto.inStockTime[0]
          listQuery.inStockEndTime = this.badStockDto.inStockTime[1]
        }
        apiGetBadStockList(listQuery).then(response => {
          this.badStockList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      getAlreadyBackList (alreadyBackDto) {
        this.tableLoadingFlag = true
        alreadyBackDto.status = 2
        alreadyBackDto.province = this.badStockDto.provinceCode
        alreadyBackDto.city = this.badStockDto.cityCode
        alreadyBackDto.pointType = this.badStockDto.pointType
        alreadyBackDto.factoryId = this.badStockDto.factoryId
        alreadyBackDto.ystsn = this.badStockDto.ystsn
        alreadyBackDto.queryYstsn = this.badStockDto.queryYstsn
        alreadyBackDto.faultAppearance = this.badStockDto.faultAppearance
        alreadyBackDto.modelId = this.badStockDto.modelId
        apiGetBadStockList(alreadyBackDto).then(response => {
          this.alreadyBackList = response.data
          this.pagination1.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      getAlreadyReceiveList (alreadyReceiveDto) {
        this.tableLoadingFlag = true
        alreadyReceiveDto.status = 3
        alreadyReceiveDto.province = this.badStockDto.provinceCode
        alreadyReceiveDto.city = this.badStockDto.cityCode
        alreadyReceiveDto.pointType = this.badStockDto.pointType
        alreadyReceiveDto.factoryId = this.badStockDto.factoryId
        alreadyReceiveDto.ystsn = this.badStockDto.ystsn
        alreadyReceiveDto.queryYstsn = this.badStockDto.queryYstsn
        alreadyReceiveDto.faultAppearance = this.badStockDto.faultAppearance
        alreadyReceiveDto.modelId = this.badStockDto.modelId
        apiGetBadStockList(alreadyReceiveDto).then(response => {
          this.alreadyReceiveList = response.data
          this.pagination2.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onSelected (data) {             // 省市区联动回调
        this.badStockDto.provinceCode = data.province.code
      },
      // 条件查询
      searchDate () {
        let listQuery = {
          pageNumber: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          province: this.badStockDto.provinceCode,
          city: this.badStockDto.cityCode,
          pointType: this.badStockDto.pointType,
          queryYstsn: this.badStockDto.queryYstsn,
          status: 5,
          factoryId: this.badStockDto.factoryId,
          ystsn: this.badStockDto.ystsn,
          faultAppearance: this.badStockDto.faultAppearance,
          modelId: this.badStockDto.modelId
        }
        this.badStockList = []
        this.pagination.totalRecords = 0
        this.getBadStockList(listQuery)
        let alreadyBackDto = {
          pageNumber: this.pagination1.currentPage,
          pageSize: this.pagination1.pageSize,
          province: this.badStockDto.provinceCode,
          city: this.badStockDto.cityCode,
          pointType: this.badStockDto.pointType,
          queryYstsn: this.badStockDto.queryYstsn,
          status: 2,
          factoryId: this.badStockDto.factoryId,
          faultAppearance: this.badStockDto.faultAppearance,
          modelId: this.badStockDto.modelId
        }
        this.alreadyBackList = []
        this.pagination1.totalRecords = 0
        this.getAlreadyBackList(alreadyBackDto)
        let alreadyReceiveDto = {
          pageNumber: this.pagination2.currentPage,
          pageSize: this.pagination2.pageSize,
          province: this.badStockDto.provinceCode,
          city: this.badStockDto.cityCode,
          pointType: this.badStockDto.pointType,
          queryYstsn: this.badStockDto.queryYstsn,
          status: 2,
          factoryId: this.badStockDto.factoryId,
          faultAppearance: this.badStockDto.faultAppearance,
          modelId: this.badStockDto.modelId
        }
        this.alreadyReceiveList = []
        this.pagination2.totalRecords = 0
        this.getAlreadyReceiveList(alreadyReceiveDto)
      },
      // 弹出维修一览界面
      onBtnRepairHistory (row) {
        this.detailDialogVisible = true
        this.ystsn = row.ystsn
      },
      // 关闭弹出框
      onBtnCancel () {
        this.detailTableLoadingFlag = false
        this.tableLoadingFlag = false
        this.detailDialogVisible = false
      },
      // 改变返回工厂
      returnFactoryChange () {
        this.searchDate()
      },
      // 单个设备返还
      oneDeviceReturn (row) {
        let array = [row.id]
        let ystsn = [row.ystsn]
        this.$router.push({
          path: '/stock/logistic',
          query: {
            type: 2,
            factoryId: row.returnFactoryId,
            idArrays: array,
            ystsn: ystsn
          }
        })
      },
      // 打开特殊返厂确认框
      specialReturnConfirm () {
        this.specialReturnBoxVisible = true
        this.returnfactoryId = null
      },
      // 特殊返厂
      specialReturnReturn () {
        var ystsn = []
        for (let i in this.multipleSelectionList) {
          this.idArrays[i] = this.multipleSelectionList[i].id
          ystsn[i] = this.multipleSelectionList[i].ystsn
        }
        this.$router.push({
          path: '/stock/logistic',
          query: {
            type: 2,
            factoryId: this.returnfactoryId,
            idArrays: this.idArrays,
            ystsn: ystsn
          }
        })
      },
      // 选择返回
      returnDevice () {
        if (this.multipleSelectionList.length === 0) {
          this.$alert('请选择需要返还的设备', '返还失败', {
            confirmButtonText: '确定'
          })
          return
        }
        let factoryId = null
        var ystsn = []
        for (let i in this.multipleSelectionList) {
          if (factoryId === null) {
            factoryId = this.multipleSelectionList[i].returnFactoryId
            this.idArrays[i] = this.multipleSelectionList[i].id
            ystsn[i] = this.multipleSelectionList[i].ystsn
          } else {
            if (factoryId !== this.multipleSelectionList[i].returnFactoryId) {
              this.idArrays = []
              this.$alert('所选设备返还不同工厂，请分批返还', '返还失败', {
                confirmButtonText: '确定'
              })
              return
            } else {
              this.idArrays[i] = this.multipleSelectionList[i].id
              ystsn[i] = this.multipleSelectionList[i].ystsn
            }
          }
        }
        this.$confirm('此操作返回设备:' + this.multipleSelectionList.length + '台', '确认返还', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push({
            path: '/stock/logistic',
            query: {
              type: 2,
              factoryId: factoryId,
              idArrays: this.idArrays,
              ystsn: ystsn
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消返还'
          })
        })
      },
      selectionChange (val) {
        this.multipleSelectionList = val
      }
    }
  }
</script>
